﻿using System;
using System.Windows;
using System.Windows.Markup;

// Register the extention in the Microsoft's default namespaces
[assembly: System.Windows.Markup.XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "personalplaner.common.mvvm.binding")]
[assembly: System.Windows.Markup.XmlnsDefinition("http://schemas.microsoft.com/winfx/2007/xaml/presentation", "personalplaner.common.mvvm.binding")]
[assembly: System.Windows.Markup.XmlnsDefinition("http://schemas.microsoft.com/winfx/2008/xaml/presentation", "personalplaner.common.mvvm.binding")]

namespace personalplaner.common.mvvm.binding
{
	[MarkupExtensionReturnType(typeof(object))]
	[ContentProperty("Key")]
    public class FocusBindingExtension : BindingDecoratorBase
    {
		/// <summary>
		/// default constructor
		/// </summary>
		public FocusBindingExtension()
		{
		}

		/// <summary> 
        /// Convenience constructor.  Sets most fields to default values.
        /// </summary>
        /// <param name="path">source path </param>
		public FocusBindingExtension(string path) 
        {
            if (path != null) 
            { 
                if (System.Windows.Threading.Dispatcher.CurrentDispatcher == null)
                    throw new InvalidOperationException();  // This is actually never called since CurrentDispatcher will throw if null. 

                Path = new PropertyPath(path);
            } 
        }

        public override object ProvideValue(IServiceProvider provider)
        {
            DependencyObject elem;
            DependencyProperty prop;
            if (base.TryGetTargetItems(provider, out elem, out prop))
            {
                FocusController.SetFocusableProperty(elem, prop);
            }

            return base.ProvideValue(provider); 
        }
    }
}